package cn.gong.jizhang.datacenter.db;

import cn.gong.jizhang.manager.ContextManager;
import cn.gong.jizhang.utils.DebugUtils;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class BaseDb {
	protected AppSQLiteOpenHelper dbOpenHelper;

	protected BaseDb() {
		Context context = ContextManager.getInstance().getContext();
		dbOpenHelper = new AppSQLiteOpenHelper(context);
	}
	
	protected void closeDb(SQLiteDatabase db) {
		if (db != null && db.isOpen()) {
			db.close();
		}
	}

	protected void closeCursor(Cursor cursor) {
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
	}

	protected SQLiteDatabase getDb() {
		return dbOpenHelper.getReadableDatabase();
	}

	protected void clearTable(String table, SQLiteDatabase db) {
		clearTable(table, "id", db);
	}

	protected void clearTable(String table, String idName, SQLiteDatabase db) {
		Cursor cursor = db.rawQuery("select * from " + table, null);
		while (cursor.moveToNext()) {
			long id = cursor.getLong(cursor.getColumnIndex(idName));
			db.execSQL("delete from " + table + " WHERE " + idName + "=?", new Object[] { id });
		}
	}

	// 一些打印信息的方法
	protected void debug(int msg) {
		debug(String.valueOf(msg));
	}

	protected void debug(long msg) {
		debug(String.valueOf(msg));
	}

	protected void debug(String msg) {
		DebugUtils.debug(msg, getClass());
	}

	protected void debug(String name, float msg) {
		debug(name, String.valueOf(msg));
	}

	protected void debug(String name, int msg) {
		debug(name, String.valueOf(msg));
	}

	protected void debug(String name, long msg) {
		debug(name, String.valueOf(msg));
	}

	protected void debug(String name, String msg) {
		DebugUtils.debug(name + ":" + msg, getClass());
	}

	protected void debug(String tag, String name, String msg) {
		DebugUtils.debug(tag, name + ":" + msg, getClass());
	}

	protected void error(Throwable e) {
		DebugUtils.error(e);
	}

	protected void exception(Exception e) {
		DebugUtils.exception(e);
	}

	protected void isNull(String name, Object obj) {
		DebugUtils.isNull(name, obj, getClass());
	}
}
